package com.chen.hotel.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chen.hotel.domain.Users;

import java.util.Date;
import java.util.List;


/**
 * JWT Token生成工具
 */
public class TokenUtil {

    // token的过期时间: 1天
    private static final long EXPIRE_TIME = 24 * 3600 * 1000;
    

    /**
     * 生成用户认证token
     * @param users
     * @return
     */
    public static String getToken(Users users, String secret){
        try{
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            return JWT.create().withAudience(users.getId().toString())
                    .withExpiresAt(date)
                    .sign(algorithm);
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 获取token中的用户id
     * @param token
     * @return
     */
    public static Integer getUserId(String token){
        List<String> audience = null;
        try{
            audience = JWT.decode(token).getAudience();
            return Integer.valueOf(audience.get(0));
        }catch(JWTDecodeException e){
            return null;
        }
    }

    public static boolean verify(String token, String secret){
        try{
            JWTVerifier jwtVerifier =JWT.require(Algorithm.HMAC256(secret)).build();
            jwtVerifier.verify(token);
            return true;
        }catch(Exception e){
            return false;
        }
    }
}
